using System;
using System.Collections.Generic;
using System.Text;
using System.Transactions;
using System.Xml;
using CodePlex.EnterpriseFramework;
using System.IO;
using System.Diagnostics;

namespace CodePlex.EnterpriseFramework
{
    public class SharepointHelper
    {
        public static void ProcessUpdateList(string filePath)
        {
            // Load file into xmlDocument obj
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filePath);
            // Validate and map incoming file
            xmlDoc = XmlHelper.ProcessInstance(xmlDoc);

            // Get Entity Object
            UpdateList SharepointUpdateList = Utilities.Deserialize<UpdateList>(xmlDoc);

            SharepointLists spList = new SharepointLists(SharepointUpdateList);

            // Execute the inquiry
            switch(SharepointUpdateList.Method)
            {
                case UpdateListMethod.New: AddNewItem(spList); break;
                case UpdateListMethod.Update: ; break;
                case UpdateListMethod.Delete: ; break; 
            }

            // Archive
            if (ConfigurationManager.ISArchive)
            {
                string fileName = filePath.Substring(filePath.LastIndexOf("\\"), filePath.Length - filePath.LastIndexOf("\\"));
                string archivePath = ConfigurationManager.ArchiveFolder + fileName;
                if( !File.Exists(archivePath) )
                {                    
                File.Move(filePath, archivePath);
                }
                else
                {
                    string newFileName = fileName.Substring(1, fileName.Length - 5) + "_" + System.Guid.NewGuid() + fileName.Substring(fileName.Length - 4, 4);
                    archivePath = ConfigurationManager.ArchiveFolder + newFileName;
                    File.Move(filePath, archivePath);
                }
            }
            else if (ConfigurationManager.IsDeleteMetadataFileAfterProcessing)
            {
                File.Delete(filePath);
            }            
        }

        public static string AddNewItem(SharepointLists spList)
        {
            // Initiate Sharepoint webService
            SharepointListWS.Lists listWs = new SharepointListWS.Lists();
            // Set Service Credentials
            listWs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            // Set Url
            listWs.Url =  spList.Url + "/_vti_bin/lists.asmx";

            // Open transactional scope and update sharepoint
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(ConfigurationManager.SharepointUpdateTimeout)))
            {
                // Try to update sharepoint list
                XmlNode newItemNode = listWs.UpdateListItems(spList.ListName, spList.Batch);

                // Check Result
                if (null != newItemNode.SelectSingleNode("//@ows_ID"))
                {
                    // Get inserted record id
                    string newItemID = newItemNode.SelectSingleNode("//@ows_ID").Value;
                    // Add attachments
                    foreach (SharepointLists.SPAttachmentProperties attachmentProperties in spList.Attachments)
                    {
                        // Check for the attachment
                        if (!File.Exists(attachmentProperties.FilePath))
                        {
                            EventLog.WriteEntry("splusvc", String.Format("{0} does not exist", attachmentProperties.FilePath), EventLogEntryType.Warning, 0, 0, null);
                            continue;
                        }
                        // Get file contents
                        Byte[] contents = Utilities.GetFileStream(attachmentProperties.FilePath);
                        //Update Sharepoint list
                        listWs.AddAttachment(spList.ListName, newItemID, attachmentProperties.FileName, contents);

                        if (attachmentProperties.Delete)
                            File.Delete(attachmentProperties.FilePath);
                    }
                }
                else
                {
                    throw new Exception("Sharepoint update has been failed, returned error:" + newItemNode.InnerXml);
                }
            }
            return "";
        }

        private static XmlNodeList GetXmlList(string ListName, string SharepointSiteUrl)
        {
            // Initiate Sharepoint webService
            SharepointListWS.Lists listWs = new SharepointListWS.Lists();
            // Set Service Credentials
            listWs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            // Set Url
            listWs.Url = SharepointSiteUrl + "/_vti_bin/lists.asmx";

            // Request Properties
            XmlDocument xmlDoc = new System.Xml.XmlDocument();
            XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
            XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
            XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
            ndQueryOptions.InnerXml = "<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>";
            ndViewFields.InnerXml = "";
            ndQuery.InnerXml = "";
            
            // Return the result
            //XmlNode listCollection = listWs.GetListItems(ListName, "", null, null, "", null, "");
            XmlNode listCollection = listWs.GetListItems(ListName,"",ndQuery, ndViewFields, "", ndQueryOptions, "");

            //XmlNode node = listWs.GetL
            return listCollection.SelectNodes("/*/*");
        }

    }
}
